
#include  "head.h"
int connfd;
int count;

void *fun(void *x)
{
    int ttid;
    int i =0;
    char buff[128]={0};
    while(1)
    {
        int ret = recv(connfd,buff,sizeof(buff),0);
        if(ret <= 0)
        {
            perror("recv");
            ttid = (int)x;
            pthread_exit(NULL);
        }
        if(!strcmp(buff,"quit\r\n"))
        {
            ttid = (int) x;
            close(connfd);
            //printf("ttid =%d\n",ttid);
            pthread_exit(NULL);
        }
        printf("recv:%s\n",buff);
    }
}
void test(int sig)
{
    count--;
    pthread_join(ttid,NULL);
}
int main(int argc, char *argv[])
{


    int sockfd  = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        perror("socket error");
        return -1;
    }
    printf("sockfd = %d \n",sockfd);


    struct sockaddr_in  localaddr;
    socklen_t   len  =  sizeof(struct sockaddr_in);   
    localaddr.sin_family            = AF_INET;
    localaddr.sin_port              = htons(7777);
    localaddr.sin_addr.s_addr       = inet_addr("172.16.3.33");

    struct sockaddr_in  useraddr;


    int on =1 ;
    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
    int ret = bind(sockfd, (struct sockaddr*)&localaddr,len);
    if(ret < 0)
    {
        perror("bind error");
        return -1;
    }
    printf("bind ok \n");

  

    listen(sockfd,1);

    pthread_t tid[128]  = {0};
    count = 0;
    while(count < 128)
    {
        signal(SIGUSR1,test);
        connfd = accept(sockfd,(struct sockaddr*)&useraddr,NULL);
        if(connfd < 0)
        {
            perror("accept error");
            return -1;
        }
        if(connfd > 0) 
        {
            pthread_create(&tid[count],NULL,fun,&tid[count]);
            printf("该线程tid =%lu\n",tid[count]);
            count++;
        }
        if(count == 0) 
        {
            close(connfd);
            break;
            
        }
    }

 
 close(sockfd);





    return 0;
}
